package com.chhuang.icoolvideo;

import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import com.chhuang.utils.Assert;

public class ParserVideoUrlThread implements Runnable {
	
	private List<Video> videos;
	
	public ParserVideoUrlThread(List<Video> videos) {
		super();
		this.videos = videos;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if(Assert.isValidCollection(videos)){
			initWebDriver();
			ExecutorService pool = Executors.newFixedThreadPool(2);
			for(Video video : videos){
				if(Assert.isValidString(video.getPlayUrl())){
					video = getVideoDowloadUrl(video);
					pool.execute(new DownloadVideoThread(video));
				}
			}
			webDriver.quit();
			pool.shutdown();
		}
	}
	
	private WebDriver webDriver;
	
	private void initWebDriver(){
		if(webDriver==null){
	    	File file_chrome = new File(App.CHROME_DRIVER);
	    	System.setProperty("webdriver.chrome.driver", file_chrome.getAbsolutePath());
	    	ChromeOptions options = new ChromeOptions();
	    	options.setBinary(App.CHROME_APPLICATION); 
	    	webDriver = new ChromeDriver(options);
    	}
	}
	
    private Video getVideoDowloadUrl(Video videoModel) {
    	try{
	    	webDriver.get(App.BASE_URL+videoModel.getPlayUrl());
	    	//计算广告时间
	    	int adtime = App.AD_TIME+5;
	    	Thread.sleep(2000);
	    	WebElement viderAd = webDriver.findElement(By.className("player-ad-time"));
	    	if(viderAd!=null){
	    		String text = viderAd.getText();
	    		if(Assert.isValidString(text)){
	    			adtime = Integer.parseInt(text.trim())+5;
	    		}
	    	}
	    	//广告时间过后 ，获取下载地址
	    	Thread.sleep(adtime*1000);
	    	WebElement videoPlayer = webDriver.findElement(By.id("video_player"));
	    	WebElement video = videoPlayer.findElement(By.tagName("video"));
	    	String downloadUrl = video.getAttribute("src");
	    	if(Assert.isValidString(downloadUrl)){
	    		videoModel.setDownloadUrl(downloadUrl);
	    	}
    	}catch(Exception e){
    		System.out.println(videoModel.toString());
    		e.printStackTrace();
    	}
    	
		return videoModel;
	}

}
